package com.xiaohao.server.parkmap.controller;

import cn.hutool.core.util.IdUtil;
import com.xiaohao.oss.OSSUtil;
import com.xiaohao.server.parkmap.entity.Complaint;
import com.xiaohao.server.parkmap.entity.ResponseResult;
import com.xiaohao.server.parkmap.service.ComplaintService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("complaint")
public class ComplaintController {
    @Autowired
    private Environment environment;

    @PostConstruct
    private void postConstruct() {
        String accessKeyId = environment.getProperty("aliyun.oss.access-key-id");
        String accessKeySecret = environment.getProperty("aliyun.oss.access-key-secret");
        String endpoint = environment.getProperty("aliyun.oss.endpoint");
        OSSUtil.init(accessKeyId, accessKeySecret, endpoint);
    }

    @Autowired
    private ComplaintService complaintService;


    @PostMapping
    public ResponseResult<Void> save(@RequestPart("complaint") Complaint complaint,
                                     @RequestPart(value = "picture", required = false) MultipartFile file) throws IOException {
        if (Objects.nonNull(file)) {
            OSSUtil.upload("park-map", "source/complain/" + IdUtil.simpleUUID(), file.getInputStream());
            file.getInputStream().close();
        }
        return complaintService.save(complaint) > 0 ? ResponseResult.success() : ResponseResult.error();
    }
}
